package top.huhuiyu.springboot3.service.impl;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import top.huhuiyu.springboot3.base.R;
import top.huhuiyu.springboot3.entity.TbFiles;
import top.huhuiyu.springboot3.entity.user.AuthInfo;
import top.huhuiyu.springboot3.exception.AppException;
import top.huhuiyu.springboot3.interceptor.AppInterceptor;
import top.huhuiyu.springboot3.mapper.TbFilesMapper;
import top.huhuiyu.springboot3.service.FileService;

import java.io.*;

@Transactional
@Service
@RequiredArgsConstructor
@Slf4j
public class FileServiceImpl implements FileService {
    private final TbFilesMapper tbFilesMapper;

    @Override
    public R<TbFiles> upload(MultipartFile file) {
        // 获取到上传文件
        // 要保存到指定的位置
        // 解决文件重名的问题
        log.debug("上传的文件：{}", file);
        if (file == null) {
            return R.fail("上传的文件不存在", null);
        }
        // 保存文件信息到数据库
        TbFiles tbFiles = new TbFiles();
        tbFiles.setFileName(file.getOriginalFilename());
        tbFiles.setFileSize(file.getSize());
        tbFiles.setContentType(file.getContentType());
        AuthInfo authInfo = AppInterceptor.getAuthInfo();
        tbFiles.setUserId(authInfo.getId());

        int i = tbFilesMapper.insert(tbFiles);
        if (i != 1) {
            return R.fail("上传失败，数据库添加信息失败", null);
        }
        log.debug("文件的id：{}", tbFiles.getId());
        // 通过id拼接唯一用户名
        String filename = String.format("_%s_%s", tbFiles.getId(), tbFiles.getFileName());
        // 确保目录存在
        File dir = new File(UPLOAD_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 保存文件
        try {
            InputStream is = file.getInputStream();
            OutputStream os = new FileOutputStream(new File(dir, filename));
            int len = 0;
            byte[] buffer = new byte[8 * 1024];
            len = is.read(buffer);
            while (len != -1) {
                os.write(buffer, 0, len);
                len = is.read(buffer);
            }
            os.close();
            is.close();
            return R.ok("上传成功", tbFiles);
        } catch (IOException e) {
            throw AppException.getInstance(e.getMessage());
        }
    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        TbFiles tbFiles = tbFilesMapper.selectById(id);
        if (tbFiles == null) {
            throw AppException.getInstance("文件不存在");
        }
        String filename = String.format("_%s_%s", tbFiles.getId(), tbFiles.getFileName());
        File dir = new File(UPLOAD_PATH);
        // 设置自定义应答信息
        // 设置响应头中的文件名称编码
        try {
            byte[] urlfilename = tbFiles.getFileName().getBytes("UTF-8");
            String encodename = new String(urlfilename, "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodename);
            response.setContentType(tbFiles.getContentType());
            response.setContentLengthLong(tbFiles.getFileSize());
            response.reset();

            InputStream is = new FileInputStream(new File(dir, filename));
            OutputStream os = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[8 * 1024];
            len = is.read(buffer);
            while (len != -1) {
                os.write(buffer, 0, len);
                len = is.read(buffer);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            throw AppException.getInstance("无法读取文件" + e.getMessage());
        }

    }

}
